import { create } from 'zustand'
import { fabric } from 'fabric'

interface CanvasState {
  canvas: fabric.Canvas | null
  images: fabric.Image[]
  selectedObjects: fabric.Object[]
  setCanvas: (canvas: fabric.Canvas | null) => void
  addImage: (image: fabric.Image) => void
  removeImage: (image: fabric.Image) => void
  setSelectedObjects: (objects: fabric.Object[]) => void
  clearCanvas: () => void
  saveCanvas: () => Promise<void>
  loadCanvas: () => Promise<void>
  newCanvas: () => void
}

// 扩展 fabric.Image 类型定义
declare module 'fabric' {
  namespace fabric {
    interface Image {
      originalScaleX?: number
      originalScaleY?: number
      filePath?: string  // 添加文件路径属性
    }
  }
}

export const useCanvasStore = create<CanvasState>((set, get) => ({
  canvas: null,
  images: [],
  selectedObjects: [],
  
  setCanvas: (canvas) => set({ canvas }),
  
  addImage: (image) => set((state) => ({
    images: [...state.images, image]
  })),
  
  removeImage: (image) => set((state) => ({
    images: state.images.filter((img) => img !== image)
  })),
  
  setSelectedObjects: (objects) => set({ selectedObjects: objects }),
  
  clearCanvas: () => set((state) => {
    state.canvas?.clear()
    return { images: [], selectedObjects: [] }
  }),

  saveCanvas: async () => {
    const { canvas } = get()
    if (!canvas) return

    // 获取所有图片的完整信息
    const objects = canvas.getObjects().map((obj) => {
      if (obj.type !== 'image') return null
      
      const img = obj as fabric.Image
      return {
        filePath: img.filePath,  // 保存文件路径
        left: img.left,
        top: img.top,
        scaleX: img.scaleX,
        scaleY: img.scaleY,
        angle: img.angle || 0,
        flipX: img.flipX || false,
        flipY: img.flipY || false,
        opacity: img.opacity || 1,
        originalScaleX: img.originalScaleX,
        originalScaleY: img.originalScaleY,
        width: img.width,
        height: img.height,
        zIndex: canvas.getObjects().indexOf(img)  // 保存图层顺序
      }
    }).filter(Boolean)  // 过滤掉非图片对象

    const canvasState = {
      version: '1.0',
      timestamp: Date.now(),
      viewportTransform: canvas.viewportTransform,
      width: canvas.width,
      height: canvas.height,
      backgroundColor: canvas.backgroundColor,
      objects
    }

    const jsonString = JSON.stringify(canvasState, null, 2)
    const { ipcRenderer } = window.require('electron')
    await ipcRenderer.invoke('save-canvas', jsonString)
  },

  loadCanvas: async () => {
    const { canvas } = get()
    if (!canvas) return

    const { ipcRenderer } = window.require('electron')
    const content = await ipcRenderer.invoke('open-canvas')
    if (!content) return

    try {
      const canvasState = JSON.parse(content)
      
      // 清除当前画布
      canvas.clear()
      set({ images: [], selectedObjects: [] })

      // 恢复画布基本属性
      if (canvasState.width && canvasState.height) {
        canvas.setDimensions({
          width: canvasState.width,
          height: canvasState.height
        })
      }
      if (canvasState.backgroundColor) {
        canvas.setBackgroundColor(canvasState.backgroundColor, canvas.renderAll.bind(canvas))
      }

      // 恢复视口变换
      if (canvasState.viewportTransform) {
        canvas.setViewportTransform(canvasState.viewportTransform)
      }

      // 加载所有图片
      const loadPromises = canvasState.objects.map(async (obj: any) => {
        if (!obj.filePath) return null

        return new Promise((resolve) => {
          fabric.Image.fromURL(`file://${obj.filePath}`, (img) => {
            img.set({
              filePath: obj.filePath,
              left: obj.left,
              top: obj.top,
              scaleX: obj.scaleX,
              scaleY: obj.scaleY,
              angle: obj.angle || 0,
              flipX: obj.flipX || false,
              flipY: obj.flipY || false,
              opacity: obj.opacity || 1,
              selectable: true,
              hasControls: true,
              hasBorders: true,
              lockRotation: false,
              lockScalingX: false,
              lockScalingY: false,
              originalScaleX: obj.originalScaleX,
              originalScaleY: obj.originalScaleY
            })

            canvas.add(img)
            get().addImage(img)
            resolve(img)
          })
        })
      })

      // 等待所有图片加载完成
      await Promise.all(loadPromises)

      // 恢复图层顺序
      if (canvasState.objects) {
        canvasState.objects.forEach((obj: any, index: number) => {
          const img = canvas.getObjects()[index] as fabric.Image
          if (img && obj.zIndex !== undefined) {
            canvas.moveTo(img, obj.zIndex)
          }
        })
      }

      canvas.renderAll()
    } catch (error) {
      console.error('加载画布失败:', error)
    }
  },

  newCanvas: () => {
    const { canvas } = get()
    if (!canvas) return

    // 清除当前画布
    canvas.clear()
    canvas.setViewportTransform([1, 0, 0, 1, 0, 0])  // 重置视口变换
    canvas.setBackgroundColor('#1e1e1e', canvas.renderAll.bind(canvas))  // 重置背景色
    
    // 重置状态
    set({ 
      images: [], 
      selectedObjects: [] 
    })

    // 重置画布尺寸为窗口大小
    canvas.setDimensions({
      width: window.innerWidth,
      height: window.innerHeight
    })

    canvas.renderAll()
  }
})) 